package com.cg.asm.client;

import com.alibaba.fastjson.JSON;
import com.cg.asm.client.constans.ConstantsEnum;
import com.cg.asm.client.domain.http.HttpClientResult;
import com.cg.asm.client.domain.user.UserInfo;
import com.cg.asm.client.exception.CommonJsonException;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class AsmSession {

    private static final String SESSION_KEY = "SESSION_USER_INFO";

    /**
     * 业务系统安全过滤器
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authId
     * @return
     * @throws Exception
     */
    public static boolean securityFilter(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String authId) {
        boolean resultValue;
        String returnCode;
        String returnMsg;
        String hostUrl = httpServletRequest.getHeader("Host-Url");
        if (StringUtils.isNotEmpty(hostUrl)) {
            Map<String, String> param = new HashMap<>();
            param.put("token", httpServletRequest.getHeader("Authentication-Token"));
            param.put("authId", authId);
            param.put("requestUrl", httpServletRequest.getRequestURI());
            try {
                String getUrl = hostUrl + "/auth/session/sessionUserInfo";
                HttpClientResult httpClientResult = HttpClientUtils.doPost(getUrl, param);
                Map<String, Object> data = JSON.parseObject(httpClientResult.getContent());
                if (httpClientResult.getCode() == 200) {
                    if ("error".equals(data.get("returnType"))) {
                        resultValue = false;
                    } else {
                        UserInfo userInfo = JSON.parseObject(JSON.toJSONString(data.get("returnData")), UserInfo.class);
                        if (null != userInfo) {
                            httpServletRequest.getSession().setAttribute(AsmSession.SESSION_KEY, userInfo);
                        } else {
                            httpServletRequest.getSession().removeAttribute(AsmSession.SESSION_KEY);
                        }
                        resultValue = true;
                    }
                } else {
                    resultValue = false;
                }
                returnCode = (String) data.get("returnCode");
                returnMsg = (String) data.get("returnMsg");

                String serviceSid = (String) data.get("serviceSid");
                if (StringUtils.isNotEmpty(serviceSid)) {
                    httpServletResponse.addHeader("set-cookie", "JSESSIONID=" + serviceSid + "; Path=/; HttpOnly");
                }
            } catch (Exception e) {
                returnCode = "";
                if (e.getMessage().indexOf("timeout") > -1) {
                    returnMsg = "响应请求,网络超时!";
                } else if (e.getMessage().indexOf("Connection refused: connect") > -1) {
                    returnMsg = "连接失败:与总控系统失去联系!";
                } else {
                    returnMsg = CommonJsonException.convertApiReturnMsg(e.getMessage());
                }
                resultValue = false;
            }
        } else {
            returnCode = ConstantsEnum.RESPONSE_E_AAAB.getKey();
            returnMsg = ConstantsEnum.RESPONSE_E_AAAB.getValue();
            resultValue = false;
        }

        if (resultValue == false) {
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter out = null;
            try {
                out = httpServletResponse.getWriter();
            } catch (IOException e) {
                returnCode = "";
                returnMsg = e.getMessage();
                e.printStackTrace();
            }
            try {
                out.println(CommonUtil.errorJson(returnCode, returnMsg));
            } finally {
                if (null != out) {
                    out.flush();
                    out.close();
                }
            }
        }
        return resultValue;
    }

    /**
     * 获取Session中的用户信息
     * @param request
     * @return
     */
    public static UserInfo getSessionUserInfo(HttpServletRequest request){
        return (UserInfo) request.getSession().getAttribute(AsmSession.SESSION_KEY);
    }
}
